package pers.rcl.common.util;

import java.util.*;

/**
 * 对map集合中的key进行字典升序排序，并返回拼接字符串
 */
public class MapKeySortUtil {
    public static String getMapKeySortStr(Map<String, String> map) {

        Map<String, String> sortedMap = new TreeMap<String, String>(map);
        StringBuffer res = new StringBuffer();
        int i = 0;
        for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
            if (i == 0) {
                res.append("?").append(entry.getKey()).append("=").append(entry.getValue());
                i++;
            } else {
                res.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
        }
        //将url中的空格字符替换为"+"
        return res.toString().replace(" ", "+");
    }

    /**
     * 按key进行正序排列,之间以&相连
     *
     * @param params 参数键值对
     * @return String 返回拼接好的字符串
     */
    public static String getSortParams(Map<String, String> params) {
        SortedMap<String, String> map = new TreeMap<String, String>();
        for (String key : params.keySet()) {
            map.put(key, params.get(key));
        }

        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        String str = "";
        while (iter.hasNext()) {
            String key = iter.next();
            String value = map.get(key);
            str += key + "=" + value + "&";
        }
        if (str.length() > 0) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    /**
     * 按key进行正序排列
     *
     * @param params 参数键值对
     * @return String 返回拼接好的字符串
     */
    public static String getSortParams2(Map<String, Object> params) {
        SortedMap<String, String> map = new TreeMap<String, String>();
        for (String key : params.keySet()) {
            map.put(key, (String) params.get(key));
        }

        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        String str = "";
        while (iter.hasNext()) {
            String key = iter.next();
            String value = map.get(key);
            str += key + value;
        }
        return str;
    }

    /**
     * 按key进行正序排列
     *
     * @param params 参数键值对
     * @return String 返回拼接好的字符串
     */
    public static String getSortByStrParams(Map<String, String> params) {
        SortedMap<String, String> map = new TreeMap<String, String>();
        for (String key : params.keySet()) {
            map.put(key, params.get(key));
        }

        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        String str = "";
        while (iter.hasNext()) {
            String key = iter.next();
            String value = map.get(key);
            str += key + value;
        }
        return str;
    }
}
